import logging
import uuid
from threading import local

from django.utils.deprecation import MiddlewareMixin

TRACE_IF_KEY = "trace_id"
HTTP_TRACE_KEY = "X-TRACE-ID"
logger = logging.getLogger(TRACE_IF_KEY)


class TraceIdFilter(logging.Filter):
    def filter(self, record):
        record.trace_id = getattr(local, TRACE_IF_KEY, "none")
        return True


def generate_sid():
    t_id = uuid.uuid1()
    return t_id


class TraceIdMiddleware(MiddlewareMixin):
    def process_request(self, request):
        local.trace_id = request.META.get(HTTP_TRACE_KEY, generate_sid())
        # 设置IP地址上下文
        ip_address = request.META['REMOTE_ADDR']
        logging.LoggerAdapter.extra = {'ip': ip_address}
        logger.info("+++++ request_begin: [{}] [{}] {}".format(request.path, request.method, list(request.GET.items())))

    def process_response(self, request, response):
        logger.info("request_end:[{}]".format(request.path))
        if hasattr(request, HTTP_TRACE_KEY):
            response[HTTP_TRACE_KEY] = local.trace_id
        try:
            del local.trace_id
        except AttributeError:
            pass

        return response
